﻿using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    public class VendorModelService : IVendorModelService
    {
        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IVendorModelRepository _vendorModelRepository;
        private readonly ILogger<VendorModelService> _logger;
		private readonly IHttpContextAccessor _contextAccessor;
		private readonly CSRedis.CSRedisClient _client;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="vendorModelRepository"></param>
		public VendorModelService(IVendorModelRepository vendorModelRepository, ILogger<VendorModelService> logger, IHttpContextAccessor contextAccessor, CSRedis.CSRedisClient client)
        {
            _vendorModelRepository = vendorModelRepository;
            _logger = logger;
			_contextAccessor = contextAccessor;
			client= new CSRedis.CSRedisClient("127.0.0.1:6379");
			_client = client;
		}
        /// <summary>
        /// 供应商列表
        /// </summary>
        /// <param name="input">参数</param>s
        /// <returns></returns>
        public async Task<PageOutput<Vendormodel>> GetVendormodel(VendorModelInPut input)
        {
            try
            {
				_logger.LogInformation("供应商列表显示分页查询");
				//拿到所有供应商列表
				var list = await _vendorModelRepository.GetVendormodels();
				if (!string.IsNullOrWhiteSpace(input.venDorCode))
				{
					list = list.Where(c => c.VenDorCode.Contains(input.venDorCode)).ToList();
				}
				if (!string.IsNullOrWhiteSpace(input.vendorName))
				{
					list = list.Where(c => c.VendorName.Contains(input.vendorName)).ToList();
				}
				if (!string.IsNullOrWhiteSpace(input.responsiblePhone))
				{
					list = list.Where(c => c.ResponsiblePhone.Contains(input.responsiblePhone)).ToList();
				}
				if (!string.IsNullOrWhiteSpace(input.markets))
				{
					list = list.Where(c => c.Markets == input.markets).ToList();
				}
				if (!string.IsNullOrWhiteSpace(input.salesman))
				{
					list = list.Where(c => c.Salesman == input.salesman).ToList();
				}
				if (input.useState != null)
				{
					list = list.Where(c => c.UseState == input.useState).ToList();
				}
				var result = new PageOutput<Vendormodel>()
				{
					TotalCount = list.Count(),
					PageSize = input.PageSize,
					Data = list.OrderByDescending(c=>c.CreateTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList(),
				};

				return result;
			}
            catch (Exception ex)
            {
				_logger.LogInformation("供应商列表异常"+ex.Message);
				throw;
            }
            
        }
		/// <summary>
		/// 供应商删除
		/// </summary>
		/// <param name="loginUserId">删除人</param>
		/// <param name="idList">删除id</param>
		/// <returns></returns>
		public async Task<int> DeleteVendormodels(params int[] idList)
        {
			try
			{
				var loginId = 1;
				return await _vendorModelRepository.DeleteVendormodels(loginId, idList);
			}
			catch (Exception ex)
			{
				_logger.LogInformation("供应商列表删除异常" + ex.Message);
				throw;
			}
        }
		/// <summary>
		/// 供应商添加
		/// </summary>
		/// <param name="entity">实体</param>
		/// <returns></returns>
		public async Task<int> AddVendormodels(Vendormodel entity)
		{
			try
			{
				entity.VenDorCode = YitIdHelper.NextId().ToString();
				entity.CreateTime = DateTime.Now;
				entity.UpdateTime = DateTime.Now;
				entity.CreateBy = 1;
				entity.IsDel = false;
				return await _vendorModelRepository.AddVendormodels(entity);
			}
			catch (Exception ex)
			{
				_logger.LogInformation("供应商添加异常" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 供应商详情
		/// </summary>
		/// <param name="vendorSnowId">主键</param>
		/// <returns></returns>
		public async Task<Vendormodel> DetailVendormodel(int vendorSnowId)
		{
			try
			{
				
				// 构建缓存键，使用 vendorSnowId 作为一部分确保唯一性
				var cacheKey = $"DetailVendormodel_{vendorSnowId}";
				var redisVendor = await _client.GetAsync<Vendormodel>(cacheKey);
				if(redisVendor == null)
				{
					redisVendor= await _vendorModelRepository.DetailVendormodel(vendorSnowId);
					// 设置缓存过期时间为 50 分钟到 53 分钟之间的随机值
					int cacheExpirationSeconds = 3000000 + new Random().Next(1, 300000);
					TimeSpan expirationTime = TimeSpan.FromMilliseconds(cacheExpirationSeconds);
					await _client.SetAsync(cacheKey, redisVendor, expirationTime);
				}
				return redisVendor;
			}
			catch (Exception ex)
			{
				_logger.LogInformation("供应商详情异常" + ex.Message);
				throw;
			}
		}
		/// <summary>
		/// 供应商修改
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		
		public async Task<int> UpdateVendormodels(Vendormodel entity)
		{
			try
			{
				var updatedEntityCount = await _vendorModelRepository.UpdateVendormodels(entity);

				// 更新或删除缓存
				if (updatedEntityCount > 0)
				{
					var cacheKey = $"DetailVendormodel_{entity.VendorSnowId}";

					// 从缓存中移除旧数据（可选，根据需求决定是否需要）
					await _client.DelAsync(cacheKey);

					// 如果需要重新缓存更新后的数据
					var updatedVendor = await _vendorModelRepository.DetailVendormodel(entity.VendorSnowId);
					if (updatedVendor != null)
					{
						// 设置缓存过期时间为 50 分钟到 53 分钟之间的随机值
						int cacheExpirationSeconds = 3000000 + new Random().Next(1, 300000);
						TimeSpan expirationTime = TimeSpan.FromMilliseconds(cacheExpirationSeconds);
						await _client.SetAsync(cacheKey, updatedVendor, expirationTime);
					}
				}
				return updatedEntityCount;
			}
			catch (Exception ex)
			{
				_logger.LogInformation("供应商修改异常" + ex.Message);
				throw;
			}
		}
	}
}
